<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-select :value="input.connect"  @change="changeConnect">
          <el-option
            v-for="connect in output.connects"
            :key="connect"
            :label="connect"
            :value="connect"

          ></el-option>
        </el-select>

        <el-select :value="input.schema" @change="changeSchema">
          <el-option
            v-for="schema in output.schemas"
            :key="schema.schemaName"
            :label="schema.schemaName"
            :value="schema.schemaName"
          ></el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row>
        <el-input  placeholder="输入表名/字段名/表注释/字段注释" class="padding-top padding-bottom" v-model="input.keyword" @change="searchTable">
          <el-button slot="append" icon="el-icon-search" @click="searchTable"></el-button>
        </el-input>
        <div class="table-items">
          <ul class="list-group list-inline">
              <!-- 绑定 tableName 属性，需要在右键的时候获取是哪个表上点击的 -->
              <li v-contextmenu:contextmenu :tablename="table.tableName" :tableindex = "index" v-for="(table,index) in output.tables" @click="chooseTable(index)" :class="'list-group-item list-inline-item cursor-point '+(view.tableChoose === index ? 'active':'') " >
                <i class="fa fa-table"></i>
                <span>{{table.tableName}}( {{table.comments || '未说明'}} )</span>
              </li>
          </ul>
        </div>
    </el-row>
    <el-row>
      <el-table
        :data="output.columns"
        border
        stripe
        highlight-current-row
        size="mini"
        style="width: 100%">
        <el-table-column type="index" label="顺序" width="50"></el-table-column>
        <el-table-column prop="columnName" label="列名" sortable></el-table-column>
        <el-table-column prop="typeMerge" label="类型"></el-table-column>
        <el-table-column prop="comments" label="注释"></el-table-column>
      </el-table>
    </el-row>

    <!-- 单表上的右键菜单 -->
    <v-contextmenu ref="contextmenu" @contextmenu="showContextMenu">
      <v-contextmenu-item ><i class="fa fa-file-text"></i> 模板代码...</v-contextmenu-item>
      <v-contextmenu-item @click="configDialog"><i class="fa fa-file-zip-o"></i> tkmybatis 代码生成...</v-contextmenu-item>
      <v-contextmenu-item @click="showTableColumns"><i class="fa fa-columns"></i> 属性列</v-contextmenu-item>
      <v-contextmenu-item divider></v-contextmenu-item>
      <v-contextmenu-item @click="tableProfile"><i class="fa fa-taxi"></i> 表属性</v-contextmenu-item>
    </v-contextmenu>

    <!-- tkmybatis 对话框 -->
    <el-dialog title="tkMybatis 项目代码生成" :fullscreen="true" :visible.sync="view.dialogtkVisible">
      <el-row>
        <el-col :span="6" class="padding-right">
          <div class="panel panel-default">
            <div class="panel-heading"><i class="el-icon-setting"></i> 表设置区</div>
            <div class="panel-body">
              <el-button-group class="padding-bottom">
                <el-button circle plain  size="mini" icon="el-icon-plus" @click="openAddTablesDialog"></el-button>
              </el-button-group>
              <ul class="list-group ">
                <li class="list-group-item" v-for="(tableName) in input.selectedTables">
                  <span>{{tableName}}</span>
                  <a class=" pull-right cursor-point" @click="removeCurrent(tableName)"><i class="fa fa-trash "></i> 删除</a>
                </li>
              </ul>
            </div>
          </div>

        </el-col>
        <el-col :span="18">
          <el-form :model="input.dialog.tkmybatis.form"  size="small" label-width="120px">
            <div class="panel panel-default">
              <div class="panel-heading"><i class="el-icon-setting"></i> 包配置</div>
              <div class="panel-body">
                  <el-form-item label="项目配置：">
                    <el-col :span="5">
                      <el-input v-model="input.dialog.tkmybatis.form.base" @keyup.native="autoCompleteConfig" placeholder="基础包，自动生成下面的包数据"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.projectName" placeholder="项目名称"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="基础包：">
                    <el-col :span="5" >
                      <el-input v-model="input.dialog.tkmybatis.form.entity" placeholder="entity"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.mapper" placeholder="mapper"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.controller" placeholder="controller"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.service" placeholder="service"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="数据包:">
                    <el-col :span="5" >
                      <el-input v-model="input.dialog.tkmybatis.form.vo" placeholder="vo"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.dto" placeholder="dto"></el-input>
                    </el-col>
                    <el-col :span="5" :offset="1">
                      <el-input v-model="input.dialog.tkmybatis.form.param" placeholder="param"></el-input>
                    </el-col>
                  </el-form-item>

              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading"><i class="el-icon-setting"></i> 实体配置</div>
              <div class="panel-body">
                <el-form-item label="实体相关：">
                  <el-col :span="5">
                    <el-input v-model="input.dialog.tkmybatis.form.extends" placeholder="继承自"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-input v-model="input.dialog.tkmybatis.form.excludes" placeholder="排除字段逗号分隔"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="添加支持：">
                  <el-col :span="5">
                    <el-checkbox-group v-model="input.dialog.tkmybatis.form.implements">
                      <el-checkbox label="java.io.Serializable" >Serializable</el-checkbox>
                    </el-checkbox-group>

                  </el-col>
                  <el-col :span="11" :offset="1">
                    <el-checkbox-group v-model="input.dialog.tkmybatis.form.supports">
                      <el-checkbox label="swagger">swagger</el-checkbox>
                      <el-checkbox label="lombok">lombok</el-checkbox>
                      <el-checkbox label="persistence">persistence</el-checkbox>
                    </el-checkbox-group>

                  </el-col>
                </el-form-item>

              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading"><i class="el-icon-setting"></i> 框架配置</div>
              <div class="panel-body">
                <el-form-item label="框架配置：">
                  <el-col :span="5" >
                    <el-input v-model="input.dialog.tkmybatis.form.tkMapper" placeholder="tkMapper"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-input v-model="input.dialog.tkmybatis.form.idColumn" value="id" placeholder="idColumn"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-input v-model="input.dialog.tkmybatis.form.sqlStatement" value="JDBC" placeholder="sqlStatement"></el-input>
                  </el-col>
                </el-form-item>

              </div>
            </div>

            <div class="panel panel-default">
              <div class="panel-heading"><i class="el-icon-setting"></i> 项目配置</div>
              <div class="panel-body">
                <el-form-item label="项目配置：">
                  <el-col :span="5">
                    <el-select v-model="input.dialog.tkmybatis.form.springBootVersion">
                      <el-option  value="2.0.5.RELEASE">2.0.5.RELEASE</el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-input v-model="input.dialog.tkmybatis.form.groupId" value="groupId" placeholder="groupId"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-input v-model="input.dialog.tkmybatis.form.artifactId" value="artifactId" placeholder="artifactId"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-select v-model="input.dialog.tkmybatis.form.version" placeholder="项目版本">
                      <el-option  value="1.0-SNAPSHOT">1.0-SNAPSHOT</el-option>
                    </el-select>
                  </el-col>
                </el-form-item>

              </div>
            </div>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="view.dialogtkVisible = false">取 消</el-button>
        <el-button type="primary" @click="downMybatisCode">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 表选择控件 -->
    <el-dialog title="选择表" :visible.sync = "view.chooseTableVisible">
      <table-search :connect="input.connect" :schema="input.schema" @selection-change="handleSelectionChange"></table-search>
      <div slot="footer" class="dialog-footer">
        <el-button @click="view.chooseTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTables">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import apis from '../apis'
    import contentmenu from 'v-contextmenu'
    import 'v-contextmenu/dist/index.css'
    import Vue from 'vue'
    import utils from '../utils'
    import TableSearch from "../components/TableSearch";

    Vue.use(contentmenu);

    export default {
        name: "TableHelp",
        components:{TableSearch},
        data(){
            return {
                output:{
                    connects:[],
                    schemas:[],
                    tables:[],
                    columns:[],
                    searchTables:[]
                },
                input:{
                    keyword:'',
                    connect:'',
                    schema:'',
                    table:'',
                    selectedTables:[],
                    dialog:{
                        tkmybatis:{
                            form:{
                                projectName:'',base:'',
                                tkMapper:'tk.mybatis.mapper.common.Mapper',idColumn:'id',sqlStatement:'JDBC',
                                entity:'',mapper:'',controller:'',service:'',vo:'',dto:'',param:'',
                                extends:'',excludes:'',
                                implements:['java.io.Serializable'],
                                supports:['swagger','lombok','persistence'],
                                springBootVersion:'2.0.5.RELEASE',
                                groupId:'',artifactId:'',version:'1.0-SNAPSHOT'
                            },
                            dialog:{
                                selectedTables:[]
                            }

                        }
                    }
                },
                view:{
                    tableChoose:0,
                    dialogtkVisible:false,
                    chooseTableVisible:false
                }
            }
        },
        methods:{
            changeConnect(value){
                this.input.connect = value;
                //加载 schema 列表
                apis.tablehelp.schemas(value).then(res => {
                    this.output.schemas = res.data;
                    if(this.output.schemas){
                        this.input.schema = res.data[0].schemaName;
                        this.changeSchema(this.input.schema);
                    }
                });
            },
            changeSchema(value){
                this.input.schema = value;
                apis.tablehelp.tables(this.input.connect,value).then(res =>{
                   this.output.tables = res.data;
                   // 重新选中第一张表,把搜索清空
                   this.input.keyword = '';
                   this.chooseTable(0);
                });
            },
            chooseTable(index){
                this.view.tableChoose = index;
                if(this.output.tables.length === 0){
                    //清空字段信息
                    this.output.columns = [];
                    return ;
                }

                this.input.table = this.output.tables[index].tableName;

                apis.tablehelp.columns(this.input.connect,this.input.schema,this.input.table).then(res => {
                    this.output.columns = res.data;
                    this.output.columns.forEach(column => {
                        column.comments = column.comments || '';
                        column.typeMerge = column.columnType.dataType;
                    });
                });
            },
            searchTable(){
              apis.tablehelp.searchTable(this.input.connect,this.input.schema,this.input.keyword).then(res => {
                 this.output.tables = res.data;
                 this.view.tableChoose = 0;
              });
            },
            //右键显示模板代码

            //右键菜单显示表格属性
            tableProfile(){
                let showInfos = [this.input.connect,this.input.schema,this.input.selectedTables[0]];
                this.$alert(showInfos.join('\n'),'当前表表格属性',{confirmButtonText: '确定'}).catch(cancel => {console.log(cancel);})
            },
            // 右键菜单显示表格所有列
            showTableColumns(){
                let selectedTableName = this.input.selectedTables[0];
                apis.tablehelp.columns(this.input.connect,this.input.schema,selectedTableName).then(res => {
                    let columns = res.data;
                    let columnNames = [];
                    columns.forEach(column => {columnNames.push(column.columnName)});
                    this.$alert(columnNames.join(','),'表格列列表',{confirmButtonText: '确定'}).catch(cancel => {console.log(cancel);});
                });
            },
            // 显示右键菜单
            showContextMenu(vnode){
                let tableName = vnode.elm.attributes['tablename'].value;
                let tableIndex = vnode.elm.attributes['tableindex'].value;

                this.input.selectedTables = [tableName];
                // this.view.tableChoose = parseInt(tableIndex);
                this.chooseTable(parseInt(tableIndex));
            },

            //右键打开 tkmybatis 对话框
            configDialog(vm,event){
                this.view.dialogtkVisible = true;
                //复制一份表到选择的表列表
                // this.input.selectedTables = [...this.output.tables];

            },
            // 填写基础包时，自动配置其它包内容
            autoCompleteConfig(){
                if(this.input.dialog.tkmybatis.form.base){
                    let base  = this.input.dialog.tkmybatis.form.base;
                    //如果基础输入有值，则自动填充其它输入框
                    let projectName = base;
                    let split = base.split('.');
                    if(split.length > 0){
                        projectName = split[split.length - 1];
                    }
                    Object.assign(this.input.dialog.tkmybatis.form,{
                        entity:base+'.dao.entity',
                        mapper:base+'.dao.mapper',
                        controller:base+'.web.controller',
                        service:base+'.service',
                        vo:base+'.dto.vo',
                        dto:base+'.dto',
                        param:base+'.dto.param',
                        groupId:base,
                        artifactId: projectName,
                        projectName: projectName
                    })
                }
            },
            openAddTablesDialog(){
              this.view.chooseTableVisible = true;
            },
            // 选择表，修改的时候
            handleSelectionChange(selection){
                this.input.dialog.tkmybatis.dialog.selectedTables = selection;
            },
            addTables(){
              //将临时添加的表添加到选择的表
                this.input.dialog.tkmybatis.dialog.selectedTables.forEach(table => {
                    this.input.selectedTables.push(table.tableName);
                });
                //数据去重
                this.input.selectedTables = utils.CollectionUtils.uniqueSimpleArray(this.input.selectedTables);
                this.view.chooseTableVisible = false;
            },
            // 对话框删除当前表
            removeCurrent(tableName){
                let removeIndex = -1;
                for(let i= 0;i<this.input.selectedTables.length;i++){
                    if(this.input.selectedTables[i] === tableName){
                      removeIndex = i;
                      break;
                    }
                }
                if(removeIndex !== -1){
                    this.input.selectedTables.splice(removeIndex,1);
                }
            },
            // 确定后，向服务器请求数据，并下载代码
            downMybatisCode(){
              let configs = this.input.dialog.tkmybatis.form;
              configs.tableNames = this.input.selectedTables;

              apis.tablehelp.code.tkmybatis(this.input.connect,this.input.schema,configs).then(res => {
                  // utils.downFile(apis.common.download,{baseName:res.data,modul:'tableTemplate'});
                  apis.download('projectCode',res.data,'zip')
              });
            }
        },
        created() {
            apis.tablehelp.connects().then(res => {
              this.output.connects = res.data;
              if(this.output.connects && this.output.connects.length > 0){
                  this.input.connect = this.output.connects[0];
                  this.changeConnect(this.input.connect);
              }
            });
        }
    }
</script>

<style scoped>
  .list-inline>.list-inline-item{
    margin-top: 8px;
    margin-left: 5px;
    padding: 10px 15px;
    border-radius: 5px;
  }

  .list-group-item:hover{
    background-color: #E8E7E6;
  }
  .list-group-item.active:hover{
    z-index: 2;
    color: #fff;
    background-color: #337ab7;
    border-color: #337ab7;
  }
  .table-items{
    max-height: 400px;
    overflow-y: scroll;
  }

</style>
